<template>
  <div class="category-proportion">
    <simple-pie :id="'pie' + Math.floor(Math.random()*1000)" :title="title" :data="chartData" tooltip-unit="元"></simple-pie>
  </div>
</template>

<script>
import SimplePie from "@/components/echarts/SimplePie";

export default {
  name: "CategoryProportion",
  components: {SimplePie},
  props: {
    start: Number,
    end: Number,
    dataSource: Array,
    title: {
      Type: String,
      default: '分类占比'
    }
  },
  data() {
    return {
      requested: false
    }
  },
  computed: {
    chartData: function () {
      if (!this.dataSource) {
        return [];
      }
      let map = {}
      this.dataSource
          .filter(item => this.start <= item.createTime && this.end >= item.createTime)
          .forEach(item => {
            if (map[item.categoryName]) {
              map[item.categoryName] += item.amount;
            } else {
              map[item.categoryName] = item.amount;
            }
          });

      let result = [];
      for(let key in map) {
        result.push({
          key: key,
          value: map[key]/100
        })
      }
      return result;
    }
  },
  methods: {
    async getData() {
      this.$emit('func')
    }
  },
  watch: {
    start() {
      if (!this.requested && this.start && this.end && !this.dataSource) {
        this.requested = true
        this.getData();
      }
    },
    end() {
      if (!this.requested && this.start && this.end && !this.dataSource) {
        this.requested = true
        this.getData();
      }
    }
  },
  created() {
    // this.getData();
  }
}
</script>

<style scoped lang="less">

.category-proportion {
  height: 100%;
  width: 100%;
}
</style>
